from fastapi import APIRouter, Query,UploadFile
from tortoise.expressions import Q
from app.controllers.appointment.category import category_controller
from app.schemas.base import Success, SuccessExtra,Fail
from app.schemas.appointment import *
from app.utils.upload import upload_image,upload_file

appointment_category_router = APIRouter()


@appointment_category_router.get("/list", summary="查看分类列表")
async def list_category(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        name: str = Query(None, description="分类名称"),
):
    q = Q()
    if name:
        q &= Q(name__contains=name)
    parent_menus = await category_controller.model.filter(parent_id=0).order_by("order")
    res_menu = [await category_controller.get_with_children(menu.id) for menu in parent_menus]
    # total, data = await category_controller.list_category(page=page, page_size=page_size, search=q)
    return SuccessExtra(data=res_menu, total=len(res_menu), page=page, page_size=page_size)

@appointment_category_router.get("/get", summary="查看分类")
async def get_category(
        data_id: int = Query(..., description="分类ID"),
):
    data = await category_controller.get_category(data_id=data_id)
    return Success(data=data)

@appointment_category_router.post("/create", summary="创建分类")
async def create_category(
        category_in: AppointmentCategoryCreate,
):
    await category_controller.create_category(obj_in=category_in)
    return Success(msg="创建成功")

@appointment_category_router.post("/update", summary="更新分类")
async def update_category(
        category_in: AppointmentCategoryUpdate,
):
    await category_controller.update_category(obj_in=category_in)
    return Success(msg="更新成功")

@appointment_category_router.delete("/delete", summary="删除分类")
async def delete_category(
        data_id: int = Query(..., description="分类ID"),
):
    await category_controller.delete_category(data_id=data_id)
    return Success(msg="删除成功")

@appointment_category_router.get("/tree", summary="树形分类")
async def tree_dept():
    data = await category_controller.get_tree()
    datas = [{
        "id": 0,
        "name": "全部",
        "desc": "全部",
        "order": 1,
        "parent_id": -1,
        "children": data,  # 递归构建子部门
    }]
    return SuccessExtra(data=datas)

@appointment_category_router.post("/file", summary="上传图片")
async def do_file(file: UploadFile):
    url = await upload_image(file,"appointment/category")
    if not url:
        return Fail(code=400, msg="图片格式错误")
    data = {"url": url}
    return Success(data=data)